package cn.com.cetccst.uicomponents.binding.widget;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import androidx.databinding.BindingAdapter;

//拓展<imageview>，设置Bitmap, 后面可以拓展url等
public class ImageViewBindingAdapter {
    @BindingAdapter({"bitmap"})
    public static <T extends CharSequence> void setBitmap(ImageView imageView, Bitmap bitmap) {
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            imageView.setImageDrawable(getMyIcon(imageView.getContext()));
        }

    }

    private static Drawable getMyIcon(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.applicationInfo.loadIcon(context.getPackageManager());
        } catch (PackageManager.NameNotFoundException e) {
        }
        return null;
    }
}
